package com.xh.shuati.ai.chatmemory;

import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson;
import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xh.shuati.model.entity.Conversation;
import com.xh.shuati.service.ConversationService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class MySqlBasedChatMemory implements ChatMemoryStore {


    @Resource
    private ConversationService conversationService;

    private List<ChatMessage> getConversation(Long conversationId) {
        List<ChatMessage> messages = new ArrayList<>();
        Conversation conversation = conversationService.getById(conversationId);
        if (conversation == null) {
            return messages;
        }
        String serializedData = conversation.getSerialized_data();
        if (serializedData == null) {
            return messages;
        }

        try {
            // 反序列化JSON字符串为List<ChatMessage>
            messages = messagesFromJson(serializedData);
        } catch (Exception e) {
            System.err.println("Error deserializing conversation data for ID: " + conversationId);
            e.printStackTrace();
        }
        return messages;
    }

    private void saveConversation(Long conversationId, List<ChatMessage> messages) {
        if (messages == null) {
            messages = new ArrayList<>();
        }
        Conversation conversation = new Conversation();
        conversation.setId(conversationId);

        try {
            // 序列化为JSON字节数组
            String serializedData = messagesToJson(messages);
            conversation.setSerialized_data(serializedData);
            conversationService.saveOrUpdate(conversation);
        } catch (Exception e) {
            System.err.println("Error serializing conversation data for ID: " + conversationId);
            e.printStackTrace();
        }
    }


    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        return getConversation((Long) memoryId);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        saveConversation((Long) memoryId, messages);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        // TODO: 实现通过内存ID删除持久化存储中的所有消息。
    }

}

